/*!
 * NextTopEvent JS Application ver 1.0
 * Docs & License: http://nexttopevent.com
 * (c) 2013 Du Dan
 */

var App = function () {
	return {
		// Google Analytics
		initGoogleAnalytics: function() {
			var _gaq = _gaq || [];
			_gaq.push(['_setAccount', 'UA-40624462-1']);
			_gaq.push(['_trackPageview']);
			
			(function() {
				var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
				ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
				var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
			})();
		},
		// Facebook Ads
		initFacebookAds: function() {
			adroll_adv_id = "KI4R7GAG55HCJKNIGABBUJ";
			adroll_pix_id = "2AWT4QRFGFD2FMAOK57YZM";
			(function () {
			var oldonload = window.onload;
			window.onload = function(){
			   __adroll_loaded=true;
			   var scr = document.createElement("script");
			   var host = (("https:" == document.location.protocol) ? "https://s.adroll.com" : "http://a.adroll.com");
			   scr.setAttribute('async', 'true');
			   scr.type = "text/javascript";
			   scr.src = host + "/j/roundtrip.js";
			   ((document.getElementsByTagName('head') || [null])[0] ||
				document.getElementsByTagName('script')[0].parentNode).appendChild(scr);
			   if(oldonload){oldonload()}};
			}());
		},
		// Facebook
		initFacebook: function() {
			(function(d, s, id) {
			  var js, fjs = d.getElementsByTagName(s)[0];
			  if (d.getElementById(id)) return;
			  js = d.createElement(s); js.id = id;
			  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
			  fjs.parentNode.insertBefore(js, fjs);
			}(document, 'script', 'facebook-jssdk'));
		},
		// Twitter
		initTwitter: function() {
			!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
		},
		// Google Plus
		initGooglePlus: function() {
			
		},
		// carouFredSel
		initCarouFredSel: function() {
			$('.carouFredSel').show();
			$('.carouFredSel').carouFredSel({
				circular: true,
				infinite: false,
				auto 	: {
					pauseOnHover: "resume",
				},
				items	: 4,
				direction           : "left",
				scroll : {
					items           : 1,
					duration        : 600,                        
					pauseOnHover    : true
				},
			});
		},
		initFullCalendar: function(requestEventList, requestEventDay, viewEventDay) {
			$('#calendar').fullCalendar({
				header: {
					left:   'prev',
					center: 'title',
					right:  'next'
				},
				buttonText: {
					prev: '<span class="glyphicon glyphicon-chevron-left"></span>',
					next: '<span class="glyphicon glyphicon-chevron-right"></span>'
				},
				weekMode: 'liquid',
				monthNames: ["Tháng Một","Tháng Hai","Tháng Ba", "Tháng Tư", "Tháng Năm", "Tháng Sáu", "Tháng Bảy", "Tháng Tám", "Tháng Chín", "Tháng Mười", "Tháng Mười Một", "Tháng Mười Hai" ],
				monthNamesShort: ['T.Một', 'T.Hai', 'T.Ba', 'T.Tư', 'T.Năm', 'T.Sáu', 'T.Bảy', 'T.Tám', 'T.Chín', 'T.Mười', 'T.Mười Một', 'T.Mười Hai'],
				dayNames: ['Chủ Nhật', 'Thứ Hai', 'Thứ Ba', 'Thứ Tư', 'Thứ Năm', 'Thứ Sáu', 'Thứ Bảy'],
				dayNamesShort: ['CN','Hai','Ba','Tư','Năm','Sáu','Bảy'],
				editable: false,
				events: function(start, end, callback) {
					var date = $('#calendar').fullCalendar('getDate');
					$.ajax({
						url: requestEventList,
						type: 'POST',
						dataType: 'json',
						data: {
							day: date.getDate(),
							month: date.getMonth()+1,
							year: date.getFullYear()
						},
						success: function(data) {
							var events = [];
							$.each(data, function(index, value) {
								events.push({
									title: value.title,
									start: value.start
								});
							});
							callback(events);
						}
					});
				},
	
				dayRender: function(date, element, view) {
					element.qtip({
						content: {
							text: '<p class="txt-center loading"></p>',
							ajax: {
								url : requestEventDay,
								type: 'POST',
								data: {
									day: date.getDate(),
									month: date.getMonth()+1,
									year: date.getFullYear()
								},
							},
							title: {
								text: 'Sự kiện ngày '+date.getDate()+'-'+(date.getMonth()+1)+'-'+date.getFullYear(),
							}
						},
						position: {
							at: 'center center',
							my: 'top center',
							viewport: $(window),
							effect: false
						},
						hide: {
							fixed: true,
						},
						style: {
							classes: 'qtip-wiki qtip-light qtip-shadow event-small'
						}
					});
				},
	
				// Sự kiện xảy ra khi click vào 1 ngày: chuyển qua action view events trong ngày
				dayClick: function(date, allDay, jsEvent, view) {
					(function(d){d.fn.redirect=function(a,b,c){void 0!==c?(c=c.toUpperCase(),"GET"!=c&&(c="POST")):c="POST";if(void 0===b||!1==b)b=d().parse_url(a),a=b.url,b=b.params;var e=d("<form></form");e.attr("method",c);e.attr("action",a);for(var f in b)a=d("<input />"),a.attr("type","hidden"),a.attr("name",f),a.attr("value",b[f]),a.appendTo(e);d("body").append(e);e.submit()};d.fn.parse_url=function(a){if(-1==a.indexOf("?"))return{url:a,params:{}};var b=a.split("?"),a=b[0],c={},b=b[1].split("&"),e={},d;for(d in b){var g= b[d].split("=");e[g[0]]=g[1]}c.url=a;c.params=e;return c}})(jQuery);
					$().redirect(viewEventDay, {'day': date.getDate(), 'month': date.getMonth()+1, 'year': date.getFullYear()});
				},
				viewDisplay: function(view) {
					if(view.name == 'month')
					{
						$('.fc-today').prevAll('td').addClass('fc-no-event');
						$('.fc-today').parent().prevAll().addClass('fc-no-event');
						$('#calendar').fullCalendar('refetchEvents');
					}
				},
			});
			$('.fc-today').prevAll('td').addClass('fc-no-event');
			$('.fc-today').parent().prevAll().addClass('fc-no-event');
		},
		initCalendarPicker: function(requestEventInWeek) {
			$('#calendar').calendarPicker({
				callback:function(cal){
					//$(".calendar-event").html(cal.currentDate.getHours());
					var date = cal.currentDate;
					$("#calendar-event").html('<p class="txt-center loading"></p>');
					$.ajax({
						url: requestEventInWeek,
						data: {
							day: date.getDate(),
							month: date.getMonth()+1,
							year: date.getFullYear()
						},
						type:'POST',
						success: function(data) {
							$("#calendar-event").html(data);
						}
					});
				}
			});
		},
		// Event Time CountDown
		initCountdown: function() {
			$('[data-time]').each(function() {
				var $this = $(this), finalDate = $(this).data('time');
				$this.countdown(finalDate, function(event) {
					$(this).html(event.strftime('<div class="btn-group"><span class="btn-block">%D</span> ngày</div><div class="btn-group"><span class="btn-block">:</span>&nbsp;</div><div class="btn-group"><span class="btn-block">%H</span> giờ</div><div class="btn-group"><span class="btn-block">:</span>&nbsp;</div><div class="btn-group"><span class="btn-block">%M</span> phút</div><div class="btn-group"><span class="btn-block">:</span>&nbsp;</div><div class="btn-group"><span class="btn-block">%S</span> giây</div>'));
				});
			});
		},
		// Event Map
		initMap: function() {
			function initialize() {
				var geocoder = new google.maps.Geocoder();
				var address = document.getElementById("map_address").innerHTML;
				var latitude;
				var longitude;
				geocoder.geocode({ 'address': address }, function (results, status) {
					if (status == google.maps.GeocoderStatus.OK) {
						latitude = results[0].geometry.location.lat();
						longitude = results[0].geometry.location.lng();
					} else {
						//alert("Request failed.")
						$('#map-canvas').remove();
					}
				});
				var latlng = new google.maps.LatLng(latitude, longitude);
				
				var mapOptions = {
					zoom: 8,
					center: latlng
				}
				map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
			}
			
			google.maps.event.addDomListener(window, 'load', initialize);
		},
        initRotatorSlider: function() {
            $('#slider').show().bannerRotator({
                width:520,
				height:285,
                tooltip:'text',
                duration:400,
				borderWidth:1,
                effect: 'random',
                cpanelAlign: 'bottomRight',
                navButtons: 'small',
                //imagePosition: 'center',
            });
        },
        // Logs
        initLogs: function() {
            $('.event-logs').show();
			$('.event-logs').carouFredSel({
				circular: true,
				infinite: false,
				auto 	: {
					pauseOnHover: "resume",
				},
				items	: 4,
				direction           : "bottom",
				scroll : {
					items           : 1,
					duration        : 600,                        
					pauseOnHover    : true
				},
			});
        },
        // Select tags
        initTags: function(suggestTag) {
            $("#Labels_title").select2({
                tags: true,
                minimumInputLength: 2,
                tokenSeparators: [","],
                initSelection : function (element, callback) {
                    var data = [];
                    $(element.val().split(',')).each(function(i) {
                        var item = this.split(':');
                        data.push({
                            id: item[0],
                            text: item[1]
                        });
                    });
                    element.val('');
                    callback(data);
                },
                createSearchChoice: function(term, data) {
                    if ($(data).filter(function() {
                        return this.text.localeCompare(term) === 0;
                    }).length === 0) {
                        return {
                            id: term,
                            text: term
                        };
                    }
                },
                multiple: true,
                ajax: {
                    url: suggestTag,
                    dataType: "json",
                    data: function(term, page) {
                        return {
                            q: term
                        };
                    },
                    results: function(data, page) {
                        return {
                            results: data
                        };
                    }
                }
            });
        },
	};
};
function changeTicket(label, value)
{
	$("#SearchForm_label").html(label);
	$("#SearchForm_ticket").val(value);
}